//
//  M4ThirdCameraViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/13.
//

import UIKit
import AVFoundation

class M4ThirdCameraViewController: M4BaseViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
    
    @IBOutlet weak var M4ThirdCameraView: UIView!
    
    @IBOutlet weak var M4ThirdCameraButton: UIButton!
    
    private var M4ThirdCaptureOutput: AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()
    
    private var M4ThirdCaptureSession: AVCaptureSession?
    
    private var M4ThirdTakePicture: Bool = false
    
    var M4ThirdCameraImageBlock: ((UIImage) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Tomar una foto", M4NavTitleColor: COLOR_333333)
        M4ThirdSetupCamera()
    }
    
    private func M4ThirdSetupCamera() {
        M4ThirdCaptureSession = AVCaptureSession()
        M4ThirdCaptureSession?.sessionPreset = .photo
        M4ThirdCaptureSession?.beginConfiguration()
        guard let M4ThirdCaptureDevice = AVCaptureDevice.default(for: .video),
        let captureInput = try? AVCaptureDeviceInput(device: M4ThirdCaptureDevice) else {return}
        if M4ThirdCaptureSession?.canAddInput(captureInput) == true {
            M4ThirdCaptureSession?.addInput(captureInput)
        }
        M4ThirdCaptureOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value:kCVPixelFormatType_32BGRA)] as [String : Any]
        M4ThirdCaptureOutput.alwaysDiscardsLateVideoFrames = true
        if M4ThirdCaptureSession?.canAddOutput(M4ThirdCaptureOutput) == true {
            M4ThirdCaptureSession?.addOutput(M4ThirdCaptureOutput)
        }
        let queue = DispatchQueue(label: "com.brianadvent.captureQueue")
        M4ThirdCaptureOutput.setSampleBufferDelegate(self, queue: queue)
        M4ThirdCaptureSession?.commitConfiguration()
        let captureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: M4ThirdCaptureSession ?? AVCaptureSession())
        captureVideoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        captureVideoPreviewLayer.frame = CGRect(x: 0, y: 0, width: M4ScreenWidth, height:M4ScreenWidth)
        M4ThirdCameraView.layer.insertSublayer(captureVideoPreviewLayer, at: 0)
        DispatchQueue.global(qos: .background).async {
            self.M4ThirdCaptureSession?.startRunning()
        }
    }
    
    @IBAction func M4ThirdCameraTakeClick(_ sender: UIButton) {
        M4ThirdTakePicture = true
    }
    
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        if M4ThirdTakePicture {
            self.M4ThirdCaptureSession?.stopRunning()
            DispatchQueue.main.async {
                var originImage = M4Image.M4SampleBuffer(sbuffer: sampleBuffer, orientation: .right)
                if originImage == nil {
                    self.M4ThirdCameraButton.M4EventUnavailable = false
                    self.M4ThirdTakePicture = false
                    self.M4ThirdCaptureSession?.startRunning()
                    return
                }
                originImage = M4Image.M4ImageCropped(originImg: originImage ?? UIImage(), croppedView: self.M4ThirdCameraView)
                self.M4ThirdCameraImageBlock?(originImage ?? UIImage())
                self.navigationController?.popViewController(animated: true)
            }
        }
    }

}
